<template>
  <div class="detail-container">
    <!-- 页面头部 -->
    <div class="detail-header">
      <div class="header-left">
        <el-button :icon="ArrowLeft" @click="goBack">返回</el-button>
        <div class="title-info">
          <h2>{{ detailData.groupName || '物料群组详情' }}</h2>
          <el-tag :type="detailData.status === 'ACTIVE' ? 'success' : 'warning'" size="large">
            {{ detailData.status === 'ACTIVE' ? '启用' : '禁用' }}
          </el-tag>
        </div>
      </div>
      <div class="header-right">
        <el-button type="primary" :icon="EditPen" @click="handleEdit">编辑</el-button>
        <el-button 
          :type="detailData.status === 'ACTIVE' ? 'warning' : 'success'" 
          @click="handleStatusToggle"
        >
          {{ detailData.status === 'ACTIVE' ? '禁用' : '启用' }}
        </el-button>
      </div>
    </div>

    <!-- 基本信息卡片 -->
    <el-card class="detail-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="card-title">基本信息</span>
        </div>
      </template>
      <div class="detail-content">
        <el-row :gutter="24">
          <el-col :span="8">
            <div class="detail-item">
              <label>群组编码：</label>
              <span>{{ detailData.groupCode || '-' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <label>群组名称：</label>
              <span>{{ detailData.groupName || '-' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <label>分组类型：</label>
              <el-tag v-if="detailData.groupType" type="info" size="small">
                {{ getGroupTypeLabel(detailData.groupType) }}
              </el-tag>
              <span v-else>-</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <div class="detail-item">
              <label>状态：</label>
              <el-tag :type="detailData.status === 'ACTIVE' ? 'success' : 'warning'">
                {{ detailData.status === 'ACTIVE' ? '启用' : '禁用' }}
              </el-tag>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <div class="detail-item">
              <label>描述：</label>
              <span>{{ detailData.description || '-' }}</span>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 统计信息卡片 -->
    <el-card class="detail-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="card-title">统计信息</span>
        </div>
      </template>
      <div class="detail-content">
        <el-row :gutter="24">
          <el-col :span="12">
            <div class="stat-item">
              <div class="stat-icon">
                <el-icon color="#67C23A"><Box /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ detailData.materialCount || 0 }}</div>
                <div class="stat-label">物料数量</div>
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="stat-item">
              <div class="stat-icon">
                <el-icon color="#E6A23C"><Clock /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ formatDateTime(detailData.createdTime) }}</div>
                <div class="stat-label">创建时间</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>



    <!-- 操作记录 -->
    <el-card class="detail-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="card-title">操作记录</span>
        </div>
      </template>
      <div class="detail-content">
        <el-row :gutter="24">
          <el-col :span="12">
            <div class="detail-item">
              <label>创建人：</label>
              <span>{{ detailData.createdBy || '-' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label>创建时间：</label>
              <span>{{ formatDateTime(detailData.createdTime) }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <div class="detail-item">
              <label>更新人：</label>
              <span>{{ detailData.updatedBy || '-' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label>更新时间：</label>
              <span>{{ formatDateTime(detailData.updatedTime) }}</span>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 编辑抽屉 -->
    <MaterialGroupDrawer ref="drawerRef" />
  </div>
</template>

<script setup lang="ts" name="MaterialGroupDetail">
import { ref, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { ArrowLeft, EditPen, FolderOpened, Box, Clock } from "@element-plus/icons-vue";
import MaterialGroupDrawer from "./form.vue";
import {
  getMaterialGroupById,
  updateMaterialGroup,
  enableMaterialGroup,
  disableMaterialGroup,
  type MaterialGroup
} from "@/api/modules/materialGroup";

const route = useRoute();
const router = useRouter();

const loading = ref(false);
const detailData = ref<MaterialGroup.MaterialGroupListItem>({} as MaterialGroup.MaterialGroupListItem);

// 表单抽屉引用
const drawerRef = ref<InstanceType<typeof MaterialGroupDrawer>>();

// 格式化时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-';
  return new Date(dateTime).toLocaleString('zh-CN');
};

// 获取群组类型标签
const getGroupTypeLabel = (groupType: string) => {
  const typeMap: Record<string, string> = {
    'MATERIAL_TYPE': '按物料类型',
    'PROCESS_ATTR': '按工艺属性',
    'BUSINESS_ATTR': '按业务属性',
    'PRICING_METHOD': '按计价方式'
  };
  return typeMap[groupType] || groupType;
};

// 获取详情数据
const getDetailData = async () => {
  const id = route.params.id as string;
  if (!id) {
    ElMessage.error("缺少群组ID参数");
    goBack();
    return;
  }

  loading.value = true;
  try {
    const res = await getMaterialGroupById(id);
    detailData.value = res.data;
  } catch (error) {
    console.error("获取物料群组详情失败:", error);
    ElMessage.error("获取物料群组详情失败");
  } finally {
    loading.value = false;
  }
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 编辑
const handleEdit = () => {
  const params = {
    title: "编辑",
    isView: false,
    row: { ...detailData.value },
    api: editMaterialGroup,
    getTableList: getDetailData
  };
  drawerRef.value?.acceptParams(params);
};

// 编辑物料群组
const editMaterialGroup = async (params: MaterialGroup.MaterialGroupListItem) => {
  return await updateMaterialGroup(params.id, params);
};

// 启用/禁用状态切换
const handleStatusToggle = async () => {
  try {
    const action = detailData.value.status === 'ACTIVE' ? '禁用' : '启用';
    await ElMessageBox.confirm(`确认${action}物料群组 "${detailData.value.groupName}" 吗？`, `${action}确认`, {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });
    
    if (detailData.value.status === 'ACTIVE') {
      await disableMaterialGroup(detailData.value.id);
    } else {
      await enableMaterialGroup(detailData.value.id);
    }
    
    ElMessage.success(`${action}成功`);
    getDetailData();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error("操作失败");
    }
  }
};



// 页面加载时获取数据
onMounted(() => {
  getDetailData();
});
</script>

<style scoped>
.detail-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 84px);
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.title-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.title-info h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.header-right {
  display: flex;
  gap: 12px;
}

.detail-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.detail-content {
  padding: 20px 0;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  font-size: 14px;
}

.detail-item label {
  width: 100px;
  color: #606266;
  font-weight: 500;
  flex-shrink: 0;
}

.detail-item span {
  color: #303133;
  word-break: break-all;
}

.stat-item {
  display: flex;
  align-items: center;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  border-radius: 50%;
  font-size: 24px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}
</style>